In [2]:
%matplotlib inline
import matplotlib
import pandas as pd
import numpy as np
import urllib2
import folium
import json
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import scipy
import scipy.stats as sp
import scipy.optimize as op
import statsmodels.api as sm
from scipy.stats import linregress
from scipy.optimize import curve_fit
from scipy import stats
from pandas.stats.api import ols
from datetime import datetime, date, timedelta
from matplotlib.backends.backend_pdf import PdfPages
#from matplotlib.pyplot import cm 
import platform
import sys
import glob

import matplotlib as mpl
import matplotlib.cm as cm

import pyproj
from pyproj import Proj
import simplekml
import wellapplication as wa
#import matplotlib
from pylab import rcParams
rcParams['figure.figsize'] = 15, 15

In [3]:
import UBM

In [4]:
engineroute = "H:/Google Drive/WORK/Round_Valley/Data/"
#engineroute = "E:/PROJECTS/Groundwater Chemistry"
#engineroute = "C:/Users/Brooke/Downloads/"
sys.path.append(engineroute)
import enginegetter

In [5]:
engine = enginegetter.getEngine()

In [6]:
from pylab import rcParams
rcParams['figure.figsize'] = 15, 15

Populate database from exported data


In [ ]:
systems = pd.read_csv('E:/sites.csv', memory_map=True)

In [ ]:
srcs = systems.SOURCE.unique()
vbls = systems.variable.unique()

for src in srcs:
    for vbl in vbls:
        df = systems[(systems['SOURCE']==src)&(systems['variable']==vbl)]
        df.to_sql(con=engine, name='zonal', if_exists='append',index=False)
        print(src, vbl)

In [ ]:
systems.head()

Calibration


In [ ]:
table = 'zonebudgets'
quer = "SELECT * FROM ubm.{:} WHERE SOURCE = '{:}'"
dataset = 'Surrgo'
soils = pd.read_sql_query(sql=quer.format(table,dataset),con=engine)
soils.to_clipboard()

BCM Overlap


In [8]:
#hucs overlapping bcm
table = 'zonebudgets'
huclist =[160201020602,160201020701,160202030504,160201020505,160201020506,160202030505,
          160201020603,160201020703,160201020604,160202010108,160202010105,160202010701,
          160202010102,160202010500,160202010404,160202010203,160202010804,160202010201,
          160202010401,160202011001,160202010202,160202010104,160202010803,160202010107,
          160202010301,160202010403,160202010602,160202010601,160202010106,160202010406,
          160202010405,160202010702,160202011002,160202010204,160202010109,160202010302,
          160202010402,160202010900,160202040303,160202040203,160202040102,160202040305,
          160202040401,160202040204,160202040402,160202040101,160202040104,160202040202,
          160202040306,160202040105,160202040205,160202040103,160202040403,160202040107,
          160202040106,160202040404,160202040307,160202040405,160202040206,160202020105,
          160202020104,160202020306,160202020305,160202020502,160202020602,160202020501,
          160202020405,160202020307,160202020403,160202020504,160202020404,160202020204,
          160202020205,160202020601,160202020503,160202020203,160202020603,160202020604,
          160202020107,160300050501,160300050604,160300050601,160300050608,160300050605,
          160300050607,160300050602,160300050502,160300050701,160300050503,160300050702,
          160300050706,160300050504,160300050603,160300050707,160300050505,160300050703,
          160300050705,160300050606,160300050507,160300050301,160300051001,160300051003,
          160300050704,160300051002,160300050709,160300050710,160300050302,160300050506,
          160300050303,160300051004,160300050901,160300050508,160300050902,160300050304,
          160300050509,160300050905,160300050708,160300051202,160300050205,160300051005,
          160300050903,160300050801,160300050405,160300050906,160300050804,160300050406,
          160300050802,160300050904,160300051101,160300050203,160300051203,160300050805,
          160300051102,160300050206,160300051201,160300050803,160300051006,160300051103,
          160300050404,160300050403,160300051104,160300051505,160300051702,160300051701,
          160300051204,160300051504,160300051704,160300051703,160300051205,160300051603,
          160300051601,160300050401,160300051506,160300051705,160300051503,160300051602,
          160300051508,160300051509,160300051206,160300051105,160300051507,160300051604,
          160300051502,160300051409,160300051706,160300051707,160300051407,160300051708,
          160300051709,160300051410,160300051501,160300051408,160300051411,160300051406,
          160300051405,160300051404,160300051403,160300051307,160300051401,160300051306,
          160300051305,160300051304,160300051303,160203030405,160203030102,160203030104,
          160203030208,160203030503,160203030204,160203030206,160203030303,160203030210,
          160203030201,160203030103,160203030105,160203030501,160203030209,160203030205,
          160203030502,160203030301,160203030207,160203030202,160203030304,160203030402,
          160203030211,160203030203,160203030401,160203030404,160203030302,160203030101,
          160203030403,160203011202,160203010703,160203010309,160203010504,160203010402,
          160203011504,160203010603,160203011503,160203010403,160203011402,160203010306,
          160203011501,160203011002,160203010901,160203010605,160203010801,160203010601,
          160203010304,160203010503,160203011004,160203011203,160203011109,160203011106,
          160203010302,160203010902,160203010904,160203010401,160203010602,160203010308,
          160203010301,160203010606,160203011103,160203011101,160203011107,160203011505,
          160203010105,160203011102,160203010608,160203011303,160203010701,160203010104,
          160203011304,160203011104,160203010502,160203011001,160203010103,160203010903,
          160203010102,160203010101,160203010702,160203011403,160203010303,160203010305,
          160203010607,160203011105,160203010307,160203011502,160203010604,160203010501,
          160203011201,160203011301,160203010804,160203011003,160203011108,160203010404,
          160203010704,160203010907,160203010310,160203011302,160203010905,160203011204,
          160203010805,160203010906,160203011110,160203010806,160203020202,160203020206,
          160203020204,160203020102,160203020302,160203020403,160203020105,160203020104,
          160203020103,160203020201,160203020205,160203020207,160203020401,160203020404,
          160203020203,160203020101,160203020303,160203020301,160203020402,160203020304,
          160102030404,160102030401,160102030305,160102030402,160102030307,160102030405,
          160102030306,160102030302,160102030204,160102030209,160102030104,160102030308,
          160102030208,160102030105,160102030403,160102030207,160300090204,160300080201,
          160300090107,160300070507,160300090500,160300090205,160300080303,160300080204,
          160300080203,160300080301,160300090401,160300080202,160300090303,160300070705,
          160300090301,160300090302,160300090203,160300070704,160300090206,160300070509,
          160300070703,160300070702,160300070504,160300090202,160300070506,160300090201,
          160300070701,160300070508,160300090108,160300070609,160300070610,160300070503,
          160300070505,160300090106,160300090105,160300090104,160300070605,160300070608,
          160300070607,160300070602,160300070102,160300090103,160300070606,160300070601,
          160300070310,160300070603,160300090101,160300090102,160300070604,160300070105,
          160300070208,160300070104,160300070406,160300070309,160300070308,160300070302,
          160300070301,160300070106,160300070211,160300070405,160300070207,160300060703,
          160300060705,160300070404,160300060701,160300070403,160300070307,160300070206,
          160300070402,160300060707,160300070306,160300070209,160300070210,160300070304,
          160300070305,160300070303,160300070401,160300060702,160300060706,160300060801,
          160300060704,160300060104,160300060302,160300060606,160300060603,160300060301,
          160300060106,160300060802,160300060303,160300060605,160300060803,160300060507,
          160300060310,160300060604,160300060504,160300060506,160300060110,160300060602,
          160300061408,160300060505,160300060205,160300060503,160300060203,160300060601,
          160300061404,160300060309,160300060308,160300080306,160300090403,160300080103,
          160300090406,160300090407,160300090408,160300080406,160300090409,160300090405,
          160300080502,160300080501,160300090404,160300080405,160300090306,160300080404,
          160300080403,160300080305,160300080402,160300080401,160300080304,160300090305,
          160300080302,160300090402,160300080102,160300090304,160300060101,160300060201,
          160300060903,150100100101,160300060904,150100100102,160300061206,160300060902,
          150100100202,160300061303,150100100205,160300061203,150100100105,150100100207,
          150100100109,160300061405,150100130402,160300061207,160300061402,160300060502,
          160300060307,160300061003,150100100208,160300060406,160300061101,160300061004,
          160300060204,150100100104,160300061208,150100100206,150100100503,160300061301,
          150100100204,160300060407,160300061406,160300061005,150100100108,160300061407,
          160300060901,150100130302,160300061002,160300061307,160300061102,160300061201,
          150100100203,160300061006,160300061205,160300061204,160300061103,150100130107,
          150100130108,160300060905,160300061202,160300061001,160300060405,160203040309,
          160203040401,160203040206,160203040307,160203040405,160203040305,160203040301,
          160203040103,160203040204,160203040302,160203040308,160203040508,160203040404,
          160203040303,160203040306,160203040403,160203040101,160203040202,160203040502,
          160203040105,160203040505,160203040501,160203040310,160203040207,160203040203,
          160203040504,160203040402,160203040201,160203040507,160203040102,160203040104,
          160203040205,160203040304,160203040503,160203040506,160102040501,160102040404,
          160102040303,160102040305,160102040301,160102040402,160102040401,160102040306,
          160102040302,160102040304,160102040503,160102040403,160102040308,160102040307,
          160102040504,160102020704,160102020506,160102020601,160102020502,160102020507,
          160102020706,160102020702,160102020701,160102020604,160102020508,160102020603,
          160102020703,160102020504,160102020602,160102020503,160102020705,160203081407,
          160203081406,160203081405,160203081402,160203081408,160203080210,160203081403,
          160203080209,160203081003,160203081404,160203080205,160203081409,160203081002,
          160203081005,160203080301,160203080208,160203081004,160203081502,160203080304,
          160203081006,160203080303,160203081501,160203080302,160203081503,160203080305,
          160203080904,160203081007,160203080901,160203080903,160203080902,160203081504,
          160203081008,160203081705,160203081703,160203081505,160203081101,160203081506,
          160203081704,160203081507,160203080309,160203080905,160203080306,160203081508,
          160203080801,160203081102,160203081706,160203080803,160203080310,160203081200,
          160203080802,160203081702,160203081103,160203081707,160203080307,160203081602,
          160203080308,160203081801,160203081604,160203080106,160203081605,160203081701,
          160203080701,160203081603,160203081802,160203080105,160203080104,160203081104,
          160203080702,160203080102,160203081601,160203081303,160203080103,160203081803,
          160203080605,160203080703,160203081304,160203081302,160203080602,160203080101,
          160203081804,160203080704,160203080604,160203080503,160203080502,160203081301,
          160203080603,160203080601,160203080501,160203080401,160203080403,160203080402,
          160203050502,160203050202,160203050501,160203050401,160203050102,160203050303,
          160203050505,160203050403,160203050201,160203050402,160203050504,160203050203,
          160203050304,160203050301,160203050101,160203050103,160203050302,160203050104,
          160203050503,160203050404,160203100100,160203090504,160203090502,160203090805,
          160203090308,160203090601,160203090503,160203090810,160203090203,160203090307,
          160203090306,160203090406,160203090303,160203090808,160203090310,160203090301,
          160203090305,160203090403,160203090607,160203090302,160203090704,160203090507,
          160203090804,160203090407,160203090703,160203090506,160203090604,160203090809,
          160203090701,160203090807,160203090404,160203090402,160203090205,160203090705,
          160203090505,160203090602,160203090806,160203090702,160203090405,160203090606,
          160203090802,160203090603,160203090801,160203090811,160203090803,160203090309,
          160203090501,160203090605,160203090204,160203090304]
huclist = set(huclist) - set([160202010900, 160300090500])

In [9]:
HUC, huc10 = UBM.process_huc(huclist)
variable = 'MEAN'
#ubm = UBM.get_UBM_data(huclist, engine, table)[0]
# This section pulls the individual model inputs and plots them (third figure)
quer = "SELECT HUC_12,YearMonth,{:},SOURCE,AREA,variable FROM ubm.{:} WHERE HUC_10 IN({:}) AND SOURCE IN({:})"
sources = "'UBM'"

chk = pd.read_sql_query(sql=quer.format(variable,table,','.join(huc10), sources), con=engine)
chk1 = chk[chk['HUC_12'].isin(HUC)]
chk1['dt'] = pd.to_datetime(chk1.YearMonth, errors='coerce', format='%Y%m')
piv = pd.pivot_table(chk1, index=['HUC_12', 'dt'], columns='variable', values=variable)
piv.reset_index(inplace=True)


c:\python27\arcgisx6410.4\lib\site-packages\ipykernel\__main__.py:10: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

In [10]:
piv.to_clipboard()

In [16]:
HUC, huc10 = UBM.process_huc(huclist)
#ubm = UBM.get_UBM_data(huclist, engine, table)[0]
# This section pulls the individual model inputs and plots them (third figure)
quer = "SELECT HUC_12,YearMonth,{:},SOURCE,AREA,variable FROM ubm.{:} WHERE HUC_10 IN({:}) AND SOURCE IN({:})"
sources = "'Surrgo','State Geologic Maps','SNODAS','MODIS16'"

chk = pd.read_sql_query(sql=quer.format(variable,table,','.join(huc10), sources), con=engine)
chk1 = chk[chk['HUC_12'].isin(HUC)]
chk1['dt'] = pd.to_datetime(chk1.YearMonth, errors='coerce', format='%Y%m')


c:\python27\arcgisx6410.4\lib\site-packages\ipykernel\__main__.py:9: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

In [17]:
piv = pd.pivot_table(chk1, index=['HUC_12', 'dt'], columns='variable', values=variable)
pv = pd.pivot_table(chk1, index=['HUC_12'], columns='variable', values=variable)
pv.drop([u'PET', u'precip as rain', u'snowmelt',u'snow and rain'], inplace=True, axis=1)
piv.reset_index(inplace=True)
pv.reset_index(inplace=True)
mrg1 = pd.merge(piv, pv, on='HUC_12')
mrg1.reset_index(inplace=True)

areas = chk1.drop(['YearMonth', 'SOURCE', 'variable', variable, 'dt'], axis=1)
areas.drop_duplicates(inplace=True)
mrg = pd.merge(mrg1, areas, on='HUC_12')
mrg.dropna(inplace=True)

# mrg.set_index(['HUC_12','dt'],inplace=True)

#mrg['incoming_water'] = mrg[u'precip as rain'] + mrg[u'snowmelt']

mrg.set_index(['dt'], inplace=True)
mrg.drop('index', inplace=True, axis=1)
mrg.drop_duplicates(subset=[u'HUC_12', u'PET', u'precip as rain',
                            u'snow and rain', u'snowmelt'],inplace = True)
mrg['YearMonth'] = [str(x.year) + str(x.month).zfill(2) for x in mrg.index]
#mrg1 = pd.merge(ubm, mrg, on=['HUC_12', 'YearMonth'])
#mrg1.set_index(['dt'], inplace=True)

In [15]:
mrg.columns


Out[15]:
Index([             u'HUC_12',                 u'PET',      u'precip as rain',
             u'snow and rain',            u'snowmelt',        u'conductivity',
            u'field capacity',            u'porosity', u'total soil moisture',
             u'wilting point',                u'AREA',           u'YearMonth',
               u'avail_water',          u'avail_rech',                 u'aet',
                    u'runoff',            u'recharge',                 u'eqt'],
      dtype='object')

In [18]:
mrg.to_clipboard()

In [14]:
df = UBM.zonal.runModel(mrg)
df.to_clipboard()


---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-14-137bee9fbe0c> in <module>()
----> 1 df = UBM.zonal.runModel(mrg)
      2 df.to_clipboard()

c:\python27\arcgisx6410.4\lib\site-packages\UBM\zonal.pyc in runModel(mrg, geo_k)
    134                 grp[h].ix[i, 'eqt'] = 3
    135                 grp[h].ix[i, 'runoff'] = 0
--> 136                 grp[h].ix[i, 'recharge'] = 0
    137                 grp[h].ix[i, 'aet'] = pet
    138             elif avail_water < wilt_pnt:

c:\python27\arcgisx6410.4\lib\site-packages\pandas\core\indexing.pyc in __setitem__(self, key, value)
    139             key = com._apply_if_callable(key, self.obj)
    140         indexer = self._get_setitem_indexer(key)
--> 141         self._setitem_with_indexer(indexer, value)
    142 
    143     def _has_valid_type(self, k, axis):

c:\python27\arcgisx6410.4\lib\site-packages\pandas\core\indexing.pyc in _setitem_with_indexer(self, indexer, value)
    546                 # scalar
    547                 for item in labels:
--> 548                     setter(item, value)
    549 
    550         else:

c:\python27\arcgisx6410.4\lib\site-packages\pandas\core\indexing.pyc in setter(item, v)
    475 
    476                 # reset the sliced object if unique
--> 477                 self.obj[item] = s
    478 
    479             def can_do_equal_len():

c:\python27\arcgisx6410.4\lib\site-packages\pandas\core\frame.pyc in __setitem__(self, key, value)
   2417         else:
   2418             # set column
-> 2419             self._set_item(key, value)
   2420 
   2421     def _setitem_slice(self, key, value):

c:\python27\arcgisx6410.4\lib\site-packages\pandas\core\frame.pyc in _set_item(self, key, value)
   2490         # value exception to occur first
   2491         if len(self):
-> 2492             self._check_setitem_copy()
   2493 
   2494     def insert(self, loc, column, value, allow_duplicates=False):

c:\python27\arcgisx6410.4\lib\site-packages\pandas\core\generic.pyc in _check_setitem_copy(self, stacklevel, t, force)
   1562         """
   1563 
-> 1564         if force or self.is_copy:
   1565 
   1566             value = config.get_option('mode.chained_assignment')

KeyboardInterrupt: 

S. Fork Ogden River


In [ ]:
import UBM

In [ ]:
HUC = ['160201020204','160201020203','160201020205','160201020202','160201020201']
SITE = 10137500
Label = 'S. Fork Ogden River'
fileloc = 'U:/GWP/Groundwater/Projects/BCM/Graphs/'
table = 'zonebudgets'
ubm, acft, ubmmon, acgp, mrg = UBM.plotfits(HUC,SITE,engine,fileloc,table)

In [ ]:
ubmdata = UBM.get_UBM_data(HUC, engine, table)

In [ ]:
modin = get_model_inputs(huclist,engine,table)

In [ ]:
modin.to_clipboard()

In [ ]:
modout = UBM.runModel(modin)
modout.to_clipboard()

In [ ]:
df = UBM.runModel(mrg)
x = df['runoff_acft']
y = df['runoff']

plt.scatter(x,y)

Chalk Creek


In [ ]:
HUC = [160202010307, 160202010304, 160202010306, 160202010305, 160202010303, 160202010302, 160202010301]
SITE = 10131000
Label = 'Chalk Creek'

UBM, acft, UBMmon, acgp, mrg = plotfits(HUC,SITE,Label)

Logan River


In [ ]:
HUC = [160102030303,160102030305,160102030307,160102030306,160102030302,160102030304,160102030301]
SITE = 10109000
SITE1 = 10109001

UBM, acft, UBMmon, acgp, mrg = plotfits(HUC,SITE)

Blacksmith Fork


In [ ]:
HUC = [160102030203,160102030201,160102030204,160102030202,160102030205,160102030208,160102030206,160102030207]
SITE = 10113500 
Label = 'Blacksmith Fork'
UBM, acft, UBMmon, acgp, mrg = plotfits(HUC,SITE,Label)

Currant Creek


In [ ]:
[160202010105,160202010102,160202010103,160202010104,160202010107,160202010101,160202010106]
10146400

In [ ]:
[160202010105,160202010103,160202010104]
10146000

Multiple Basins


In [ ]:
sitesHUCs = {10150500:[160202020105,160202020104,160202020306,160202020103,160202020305,160202020303,160202020302,160202020301,
                       160202020501,160202020307,160202020202,160202020201,160202020101,160202020204,160202020304,160202020205,
                       160202020106,160202020203,160202020102,160202020107], 10146000:[160202010105,160202010103,160202010104], 
             10146400:[160202010105,160202010102,160202010103,160202010104,160202010107,160202010101,160202010106],
             10113500:[160102030203,160102030201,160102030204,160102030202,160102030205,160102030208,160102030206,160102030207],
             10109000:[160102030303,160102030305,160102030307,160102030306,160102030302,160102030304,160102030301],
             10131000:[160202010307,160202010304,160202010306,160202010305,160202010303,160202010302,160202010301],
             10137500:[160201020204,160201020203,160201020205,160201020202,160201020201],
             10149400:[160202020303,160202020302,160202020301,160202020304], 
             10149000:[160202020301],
             '09288000':[140600040403,140600040402,140600040401,140600040404],
             '09285900':[140600040103,140600040304,140600040104,140600040106,140600040105,140600040301,140600040303,
                         140600040101,140600040102,140600040302],
             '09288180':[140600040506,140600040103,140600040802,140600040503,140600040304,140600040504,140600040801,
                         140600040201,140600040203,140600040804,140600040405,140600040403,140600040402,140600040204,
                         140600040202,140600040501,140600040401,140600040502,140600040104,140600040106,140600040105,
                         140600040805,140600040301,140600040303,140600040101,140600040102,140600040302,140600040404,
                         140600040505,140600040803],
             '09326500':[140600090302,140600090301,140600090303],
             '09405500':[150100080104,150100080103,150100080102,150100080106,150100080101,150100080108,150100080107,
                         150100080105,150100080109],
             '09409880':[150100080603,150100080702,150100080704,150100080701,150100080802,150100080703,150100080601,
                         150100080602],
             '09409100':[150100080702,150100080701,150100080703],
             '09414900':[150100100101,150100100102,150100100202,150100100205,150100100105,150100100207,150100100109,
                         150100100110,150100100208,150100100104,150100100206,150100100204,150100100106,150100100107,
                         150100100108,150100100203,150100100103],
             10166430:[160202010701],
             10128500:[160201010205,160201010204,160201010203,160201010206,160201010201,160201010202]}

In [ ]:
{10174500:[160300010101,160300010202,160300010203,160300010302,160300010301,160300010103,
          160300010102,160300010201,160300010303,160300010104,160300010204,160300010105],
'09408195':[150100090601,150100090603,150100090408,150100090604,150100090602],
             10215900:[1603000306],
             '09406000':[150100080209,150100080506,150100080505,150100080504,150100080207,150100080503,150100080104,
                         150100080103,150100080204,150100080102,150100080201,150100080502,150100080507,150100080106,
                         150100080208,150100080101,150100080205,150100080202,150100080108,150100080206,150100080107,
                         150100080203,150100080105,150100080109,150100080210],}

In [ ]:
for key,values in sitesHUCs.iteritems():
    print(key)
    UBM, acft, UBMmon, acgp, mrg = plotfits(values,key)

In [ ]:
mrg.set_index(['HUC_12','dt'],inplace=True)

In [ ]:


In [ ]:
mrg['YearMonth'] = [str(x.year) + str(x.month).zfill(2) for x in mrg.index]

In [ ]:
huc12list = mrg.index.get_level_values(0)

mrg['avail_water'] = np.nan
mrg['avail_rech'] = np.nan
mrg['aet'] = np.nan
mrg['runoff'] = np.nan
mrg['recharge'] = np.nan


for huc, grp in mrg.groupby(level=0):
    
    grp.ix[grp.index.min(),'avail_water'] = grp.ix[0,'precip as rain'] + grp.ix[0,'snowmelt'] + grp['field capacity'].mean()
    soil_max = grp['total soil moisture'].mean()
    field_cap = grp['field capacity'].mean()
    geo_k = grp['conductivity'].mean()
    wilt_pnt = grp['wilting point'].mean()
    
    for i, sub in grp.groupby(level=0):

        sub.ix[i,'test'] = i
        rain = sub.ix[i,'precip as rain']
        melt = sub.ix[i,'snowmelt']
        pet = sub.ix[i, 'evapotranspiration']

        if i == grp.index.min():
            sub.ix[i,'avail_water'] = rain + melt + field_cap
        else:    
            sub.ix[i,'avail_water'] = rain + melt + sub.ix[i.shift(-1

In [ ]:
mrg.drop('index',inplace=True,axis=1)

In [ ]:
mrg.set_index(['dt'],inplace=True)
mrg.drop('index',inplace=True,axis=1)

In [ ]:
UBMplus = pd.merge(UBM, df, on=['HUC_12','YearMonth'])

In [ ]:
UBMplus.to_clipboard()

In [ ]:
x = UBMplus.recharge
y = UBMplus.recharge_acft

plt.scatter(x,y)

In [ ]:
def runModel(mrg, geo_k=''):
    huc12list = mrg['HUC_12'].unique()

    mrg['avail_water'] = np.nan
    mrg['avail_rech'] = np.nan
    mrg['aet'] = np.nan
    mrg['runoff'] = np.nan
    mrg['recharge'] = np.nan
    mrg['eqt'] = np.nan

    grp = {}

    for h in huc12list:

        grp[h] = mrg[mrg['HUC_12']==h]
        grp[h] = grp[h][~grp[h].index.duplicated(keep='first')]

        soil_max = grp[h]['porosity'].mean()
        field_cap = grp[h]['field capacity'].mean()
        if geo_k == '':
            geo_k = grp[h]['conductivity'].mean()
    
        wilt_pnt = grp[h]['wilting point'].mean()
        dates = pd.date_range(start=grp[h].index.min(),end=grp[h].index.max(),freq='MS')

        for i in dates:
            rain = grp[h].ix[i,'precip as rain']
            melt = grp[h].ix[i,'snowmelt']
            pet = grp[h].ix[i,'evapotranspiration']
            if i == dates[0]:
                avail_water = rain + melt + field_cap
            elif i.month == 1:    
                avail_water = rain + melt + grp[h].ix[pd.datetime(i.year-1,12,1),'avail_water']
            else:
                avail_water = rain + melt + grp[h].ix[pd.datetime(i.year,i.month-1,1),'avail_water']

            if avail_water > soil_max:

                avail_rech = soil_max - field_cap
                grp[h].ix[i, 'aet'] = pet

                if avail_rech > geo_k:
                    grp[h].ix[i,'eqt'] = 1.1

                    grp[h].ix[i,'runoff'] = (avail_water - soil_max) + (avail_rech - geo_k)
                    grp[h].ix[i,'recharge'] = geo_k
                else:
                    grp[h].ix[i,'eqt'] = 1.2
                    grp[h].ix[i,'runoff'] = avail_water - soil_max
                    grp[h].ix[i,'recharge'] = avail_rech
            elif (avail_water < soil_max) and (avail_water > field_cap):
                grp[h].ix[i,'eqt'] = 2
                avail_rech = avail_water - field_cap
                grp[h].ix[i, 'aet'] = pet

                if avail_rech > geo_k:
                    grp[h].ix[i,'runoff'] = avail_rech - geo_k
                    grp[h].ix[i,'recharge'] = geo_k
                else:
                    grp[h].ix[i,'runoff'] = 0
                    grp[h].ix[i,'recharge'] = avail_rech
            elif (avail_water > wilt_pnt) and (avail_water < field_cap):
                grp[h].ix[i,'eqt'] = 3
                grp[h].ix[i,'runoff'] = 0
                grp[h].ix[i,'recharge'] = 0
                grp[h].ix[i, 'aet'] = pet        
            elif avail_water < wilt_pnt:
                grp[h].ix[i,'eqt'] = 4
                grp[h].ix[i,'runoff'] = 0
                grp[h].ix[i,'recharge'] = 0
                grp[h].ix[i, 'aet'] = 0
            else:
                pass

            grp[h].ix[i, 'avail_rech'] = avail_rech
            grp[h].ix[i,'avail_water'] = avail_water


    if len(huc12list) > 1:
        df = pd.concat([grp[h] for h in huc12list])

    else:
        df = grp[h]
    df['YearMonth'] = [str(x.year) + str(x.month).zfill(2) for x in df.index]

    return df

In [ ]:


In [ ]:
df['YearMonth']

In [ ]:
from scipy.interpolate import griddata
import matplotlib.cm as cm


SITE = '10131000'
meth = 'linear'#'nearest'

nw = wa.nwis('dv',SITE,'sites')#, startDT='1999-01-01')
data = nw.data
if isinstance(data.index, pd.core.index.MultiIndex):
    data.index = data.index.droplevel(0)
    
x = data.index.dayofyear
y = data.index.year
z = data.value.values

xi = np.linspace(x.min(), x.max(), 1000)
yi = np.linspace(y.min(), y.max(), 1000)
zi = griddata((x,y),z,(xi[None,:],yi[:,None]),method=meth)


cmap = plt.cm.get_cmap('RdYlBu')
norm = mpl.colors.Normalize(vmin=z.min(), vmax=z.max())
m = cm.ScalarMappable(norm=norm, cmap=cmap)
m.set_array(z)


br = plt.contourf(xi,yi,zi,color=m.to_rgba(z),cmap=cmap)
# setup the colorbar


cbar = plt.colorbar(m)
cbar.set_label('Discharge (cfs)')

plt.xlabel('Month')
plt.ylabel('Year')
plt.yticks(range(y.min(),y.max()))

mons = {'Apr': 90.25, 'Aug': 212.25, 'Dec': 334.25, 'Feb': 31, 'Jan': 1, 'Jul': 181.25, 'Jun': 151.25, 'Mar': 59.25, 'May': 120.25,
 'Nov': 304.25, 'Oct': 273.25, 'Sep': 243.25}
monnms = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']

plt.title(nw.sites.station_nm[0].title())
tickplc = []
plt.xticks([mons[i] for i in monnms], monnms)
print(y.max())
plt.grid()